// cloudfunctions/getUserPoints/index.js
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    // 检查参数
    const { userId } = event
    if (!userId) {
      return { success: false, message: '用户ID不能为空' }
    }
    
    // 查询用户积分记录
    const res = await db.collection('user_points')
      .where({ userId: userId })
      .get()
      
    // 如果没有记录，返回默认值
    if (!res.data || res.data.length === 0) {
      return {
        success: true,
        points: 0,
        totalPoints: 0,
        records: []
      }
    }
    
    // 返回用户积分信息
    const pointsData = res.data[0]
    return {
      success: true,
      points: pointsData.points || 0,
      totalPoints: pointsData.totalPoints || 0,
      records: pointsData.records || []
    }
    
  } catch (error) {
    console.error('获取用户积分失败:', error)
    return { success: false, message: '获取用户积分失败' }
  }
}